﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace Sinacor.Infra.UI.Controls.SmartClient
{
    internal class DragDropManager
    {
        FrameworkElement _element;

        public DragDropManager(FrameworkElement element)
        {
            _element = element;

            _element.PreviewDragEnter += new DragEventHandler(PreviewHandler);
            _element.PreviewDragOver += new DragEventHandler(PreviewHandler);
            _element.PreviewDragLeave += new DragEventHandler(PreviewHandler);
            _element.PreviewDrop += new DragEventHandler(PreviewHandler);

            _element.DragEnter += new DragEventHandler(DragEnterHandler);
            _element.DragOver += new DragEventHandler(DragOverHandler);
            _element.DragLeave += new DragEventHandler(DragLeaveHandler);
            _element.Drop += new DragEventHandler(DropHandler);
        }

        private void OnDragDrop(DragEventArgs e)
        {
            DependencyObject dropTarget = null;

            if (e.OriginalSource is IItemsControlDropTarget || e.OriginalSource is IDropTarget)
            {
                dropTarget = e.OriginalSource as DependencyObject;
            }
            else
            {
                dropTarget = ControlHelper.FindParent((DependencyObject)e.OriginalSource, p => p is IItemsControlDropTarget || p is IDropTarget) as DependencyObject;
            }

            if (dropTarget != null)
                e.Source = dropTarget;
        }

        void PreviewHandler(object sender, DragEventArgs e)
        {
            this.OnDragDrop(e);
        }

        void DragEnterHandler(object sender, DragEventArgs e)
        {
            this.OnDragDrop(e);

            SinacorDragDrop.SetIsDragOver(_element, true);
        }

        void DragOverHandler(object sender, DragEventArgs e)
        {
            this.OnDragDrop(e);
        }

        void DragLeaveHandler(object sender, DragEventArgs e)
        {
            this.OnDragDrop(e);

            SinacorDragDrop.SetIsDragOver(_element, false);
        }

        void DropHandler(object sender, DragEventArgs e)
        {
            this.OnDragDrop(e);

            SinacorDragDrop.SetIsDragOver(_element, false);
        }
    }
}